<template>
  <div class="payment-notice-container">
    <a-spin :loading="loading" class="w-full">
      <!-- 支付通知列表卡片 -->
      <a-card title="支付通知列表" class="notice-card" :bordered="false">
        <template #extra>
          <a-space>
            <a-button type="text" :loading="loading" @click="loadPaymentNotice">
              <template #icon><IconRefresh /></template>
              刷新
            </a-button>
            <a-button
              v-if="!readonly"
              v-perm="['lindi:subsidyApplicationPayNotice:add']"
              type="primary"
              :loading="editLoading"
              @click="showEditModal()"
            >
              <template #icon><IconPlus /></template>
              新增支付通知
            </a-button>
          </a-space>
        </template>

        <!-- 支付通知列表 -->
        <div
          v-if="paymentNoticeList && paymentNoticeList.length > 0"
          class="notice-list"
        >
          <div
            v-for="(notice, index) in paymentNoticeList"
            :key="notice.subsidyApplicationPayNoticeId || index"
            class="notice-item"
          >
            <a-card class="notice-item-card" size="small">
              <template #title>
                <div
                  class="notice-title"
                  @click="
                    toggleCollapse(
                      notice.subsidyApplicationPayNoticeId || index
                    )
                  "
                >
                  <a-space>
                    <IconDown
                      v-if="
                        !isCollapsed(
                          notice.subsidyApplicationPayNoticeId || index
                        )
                      "
                      class="collapse-icon"
                    />
                    <IconRight v-else class="collapse-icon" />
                    <span>{{ notice.payTitle || `支付通知 ${index + 1}` }}</span>
                  </a-space>
                </div>
              </template>
              <template #extra>
                <a-space>
                  <a-button
                    v-if="!readonly"
                    v-perm="['lindi:subsidyApplicationPayNotice:update']"
                    type="text"
                    size="small"
                    @click="showEditModal(notice)"
                  >
                    <template #icon><IconEdit /></template>
                    编辑
                  </a-button>
                  <a-button
                    v-if="!readonly"
                    v-perm="['lindi:subsidyApplicationPayNotice:delete']"
                    type="text"
                    size="small"
                    status="danger"
                    @click="deletePaymentNotice(notice, index)"
                  >
                    <template #icon><IconDelete /></template>
                    删除
                  </a-button>
                </a-space>
              </template>

              <div
                v-show="
                  !isCollapsed(notice.subsidyApplicationPayNoticeId || index)
                "
                class="notice-content"
              >
                <!-- 基本信息 -->
                <a-descriptions
                  :column="2"
                  size="medium"
                  class="notice-descriptions"
                >
                  <a-descriptions-item label="通知时间">
                    <span class="time-text">{{ notice.noticeDate }}</span>
                  </a-descriptions-item>
                  <a-descriptions-item label="支付通知标题">
                    <span class="title-text">{{
                      notice.payTitle || "暂无标题"
                    }}</span>
                  </a-descriptions-item>
                  <a-descriptions-item label="支付说明" :span="2">
                    <span class="description-text">{{
                      notice.payExplain || "暂无说明"
                    }}</span>
                  </a-descriptions-item>
                </a-descriptions>

                <!-- 镇街支付明细 -->
                <div class="payment-details-section">
                  <h5 class="section-title">镇街支付明细</h5>
                  <div
                    v-if="
                      notice.townPaymentList &&
                      notice.townPaymentList.length > 0
                    "
                    class="payment-details-table"
                  >
                    <a-table
                      :data="notice.townPaymentList"
                      :pagination="false"
                      :bordered="true"
                      size="small"
                      class="payment-table"
                    >
                      <template #columns>
                        <a-table-column
                          title="镇街名称"
                          data-index="townName"
                          align="center"
                          :width="120"
                        />
                        <a-table-column
                          title="验收亩数"
                          data-index="acceptAcreage"
                          align="center"
                          :width="110"
                        >
                          <template #cell="{ record }">
                            {{ record.acceptAcreage || 0 }} 亩
                          </template>
                        </a-table-column>
                        <a-table-column
                          title="总金额(万元)"
                          data-index="totalAmount"
                          align="center"
                          :width="120"
                        >
                          <template #cell="{ record }">
                            <span class="amount-text">{{
                              record.totalAmount || 0
                            }}</span>
                          </template>
                        </a-table-column>
                        <a-table-column
                          a-table-column
                          title="支付比例(%)"
                          data-index="paymentRadio"
                          align="center"
                          :width="110"
                        >
                          <template #cell="{ record }">
                            {{ record.paymentRadio || 0 }}
                          </template>
                        </a-table-column>
                        <a-table-column
                          title="支付金额(万元)"
                          data-index="currentPaymentAmount"
                          align="center"
                          :width="130"
                        >
                          <template #cell="{ record }">
                            <span class="current-amount-text">{{
                              record.currentPaymentAmount || 0
                            }}</span>
                          </template>
                        </a-table-column>
                        <a-table-column
                          title="备注"
                          data-index="remark"
                          align="left"
                        >
                          <template #cell="{ record }">
                            {{ record.remark || "无" }}
                          </template>
                        </a-table-column>
                      </template>
                    </a-table>

                    <!-- 合计信息 -->
                    <div class="payment-summary">
                      <a-descriptions
                        :column="2"
                        size="small"
                        class="summary-descriptions"
                      >
                        <a-descriptions-item label="总金额">
                          <span class="summary-amount-text"
                            >{{
                              getNoticeTotal(notice, "totalAmount")
                            }}
                            万元</span
                          >
                        </a-descriptions-item>
                        <a-descriptions-item label="本次支付总额">
                          <span class="current-total-amount-text"
                            >{{
                              getNoticeTotal(notice, "currentPaymentAmount")
                            }}
                            万元</span
                          >
                        </a-descriptions-item>
                      </a-descriptions>
                    </div>
                  </div>
                  <a-empty
                    v-else
                    description="暂无支付明细"
                    class="empty-details"
                    size="small"
                  />
                </div>

                <!-- 支付通知附件 -->
                <div class="attachments-section">
                  <h5 class="section-title">支付通知附件</h5>
                  <div
                    v-if="notice.fileVOList && notice.fileVOList.length > 0"
                    class="attachments-list"
                  >
                    <div
                      v-for="file in notice.fileVOList"
                      :key="file.id"
                      class="attachment-item"
                    >
                      <div class="file-info">
                        <div class="file-icon">
                          <IconFile v-if="!isImageFile(file.file?.fileName)" />
                          <IconImage v-else />
                        </div>
                        <div class="file-details">
                          <p class="file-name">
                            {{ file.file?.fileName || "未知文件" }}
                          </p>
                          <p class="file-size">
                            {{ formatFileSize(file.fileSize) }}
                          </p>
                        </div>
                      </div>
                      <div class="file-actions">
                        <a-button
                          v-perm="['lindi:subsidyApplicationPayNotice:get']"
                          type="text"
                          size="small"
                          @click="downloadFile(file)"
                        >
                          <template #icon><IconDownload /></template>
                          下载
                        </a-button>
                        <a-button
                          v-if="isImageFile(file.file?.fileName)"
                          v-perm="['lindi:subsidyApplicationPayNotice:get']"
                          type="text"
                          size="small"
                          @click="window.open(file.file?.fileUrl, '_blank')"
                        >
                          <template #icon><IconEye /></template>
                          预览
                        </a-button>
                      </div>
                    </div>
                  </div>
                  <a-empty
                    v-else
                    description="暂无附件"
                    class="empty-attachments"
                    size="small"
                  />
                </div>
              </div>
            </a-card>
          </div>
        </div>

        <a-empty v-else description="暂无支付通知信息" class="empty-notice" />
      </a-card>
    </a-spin>

    <!-- 编辑支付通知弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      :title="
        editForm.subsidyApplicationPayNotice ? '编辑支付通知' : '新增支付通知'
      "
      width="1200px"
      :footer="false"
      :mask-closable="false"
      @cancel="resetEditForm"
      @before-close="resetEditForm"
    >
      <div class="edit-modal-content">
        <a-form
          ref="editFormRef"
          :model="editForm"
          :rules="editRules"
          layout="vertical"
        >
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="noticeDate" label="通知时间" required>
                <a-date-picker
                  v-model="editForm.noticeDate"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择通知时间"
                  class="w-full"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="payTitle" label="支付通知标题">
                <a-input
                  v-model="editForm.payTitle"
                  placeholder="请输入支付通知标题"
                  class="w-full"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item field="payExplain" label="支付说明">
                <a-input
                  v-model="editForm.payExplain"
                  placeholder="请输入支付说明"
                  class="w-full"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 镇街支付明细编辑 -->
          <a-form-item field="townPaymentList" label="镇街支付明细">
            <div class="town-payment-edit-section">
              <div class="edit-table-header">
                <span class="edit-table-title">镇街支付明细</span>
              </div>

              <div
                v-if="
                  townPaymentDisplayList && townPaymentDisplayList.length > 0
                "
                class="edit-table-container"
              >
                <a-table
                  :data="townPaymentDisplayList"
                  :pagination="false"
                  :bordered="true"
                  size="small"
                  class="edit-payment-table"
                >
                  <template #columns>
                    <a-table-column title="镇街名称" :width="140">
                      <template #cell="{ record, rowIndex }">
                        <span class="readonly-field">{{
                          record.townName
                        }}</span>
                      </template>
                    </a-table-column>
                    <a-table-column title="验收亩数" :width="120">
                      <template #cell="{ record, rowIndex }">
                        <span class="readonly-field"
                          >{{ record.acceptAcreage || 0 }} 亩</span
                        >
                      </template>
                    </a-table-column>
                    <a-table-column title="总金额(万元)" :width="130">
                      <template #cell="{ record, rowIndex }">
                        <span class="readonly-field"
                          >{{ record.totalAmount || 0 }} 万元</span
                        >
                      </template>
                    </a-table-column>
                    <a-table-column title="剩余支付比例(%)" :width="140">
                      <template #cell="{ record, rowIndex }">
                        <span class="remaining-ratio-display">
                          {{ record.remainingPaymentRatio || 0 }}%
                        </span>
                      </template>
                    </a-table-column>
                    <a-table-column title="当前支付比例(%)" :width="140">
                      <template #cell="{ record, rowIndex }">
                        <a-input
                          v-model="record.currentPaymentRatio"
                          placeholder="支付比例"
                          size="small"
                          @input="calculateCurrentPaymentAmount(record)"
                        />
                      </template>
                    </a-table-column>
                    <a-table-column title="当前支付金额(万元)" :width="150">
                      <template #cell="{ record, rowIndex }">
                        <span class="current-payment-display">
                          {{ record.currentPaymentAmount || 0 }} 万元
                        </span>
                      </template>
                    </a-table-column>
                    <a-table-column title="备注" :width="150">
                      <template #cell="{ record, rowIndex }">
                        <a-input
                          v-model="record.remark"
                          placeholder="备注"
                          size="small"
                        />
                      </template>
                    </a-table-column>
                  </template>
                </a-table>

                <!-- 编辑模式合计信息 -->
                <div class="edit-payment-summary">
                  <a-descriptions
                    :column="2"
                    size="small"
                    class="edit-summary-descriptions"
                  >
                    <a-descriptions-item label="总金额">
                      <span class="edit-summary-amount-text"
                        >{{ editTotalAmount }} 万元</span
                      >
                    </a-descriptions-item>
                    <a-descriptions-item label="本次支付总额">
                      <span class="edit-current-total-amount-text"
                        >{{ editCurrentTotalPaymentAmount }} 万元</span
                      >
                    </a-descriptions-item>
                  </a-descriptions>
                </div>
              </div>

              <a-empty
                v-else
                description="暂无支付明细，请添加"
                class="empty-edit-details"
              />
            </div>
          </a-form-item>

          <a-form-item field="fileList" label="支付通知附件">
            <!-- 文件上传组件 -->
            <uploadFile
              ref="fileUploadRef"
              :file-source="fileSource.lindi_subsidy_payment_notice_file?.key"
              @upload-success="handleUploadSuccess"
            />

            <!-- 已有附件展示 -->
            <div v-if="existingFiles.length > 0" class="existing-files-section">
              <div class="existing-files-title">已有附件</div>
              <div class="existing-files-list">
                <div
                  v-for="file in existingFiles"
                  :key="file.id || file.fileId"
                  class="existing-file-item"
                >
                  <div class="file-info">
                    <div class="file-icon">
                      <IconFile v-if="!isImageFile(file.fileName)" />
                      <IconImage v-else />
                    </div>
                    <div class="file-details">
                      <p class="file-name" :title="file.fileName">
                        {{ file.fileName }}
                      </p>
                      <p class="file-size">
                        {{ formatFileSize(file.fileSize) }}
                      </p>
                    </div>
                  </div>
                  <div class="file-actions">
                    <a-button
                      type="text"
                      size="small"
                      @click="downloadFile(file)"
                    >
                      <template #icon><IconDownload /></template>
                      下载
                    </a-button>
                    <a-button
                      v-if="isImageFile(file.fileName)"
                      type="text"
                      size="small"
                      @click="window.open(file.file?.fileUrl, '_blank')"
                    >
                      <template #icon><IconEye /></template>
                      预览
                    </a-button>
                    <a-button
                      type="text"
                      size="small"
                      status="danger"
                      @click="removeExistingFile(file)"
                    >
                      <template #icon><IconDelete /></template>
                      删除
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </a-form-item>

          <!-- 操作按钮 -->
          <div class="edit-actions">
            <a-space size="large">
              <a-button size="large" @click="resetEditForm">取消</a-button>
              <a-button
                type="primary"
                size="large"
                :loading="saveLoading"
                @click="handleSave"
              >
                保存
              </a-button>
            </a-space>
          </div>
        </a-form>
      </div>
    </a-modal>

    <!-- 文件预览弹窗 -->
    <a-modal
      v-model:visible="previewModalVisible"
      :title="previewFile?.fileName || '文件预览'"
      width="80%"
      :footer="false"
    >
      <div class="preview-content">
        <img
          v-if="previewFile && isImageFile(previewFile.fileName)"
          :src="previewFile.fileUrl"
          :alt="previewFile.fileName || '预览图片'"
          class="preview-image"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconEdit,
  IconFile,
  IconImage,
  IconDownload,
  IconEye,
  IconPlus,
  IconInfo,
  IconDelete,
  IconDown,
  IconRight,
  IconRefresh,
} from "@arco-design/web-vue/es/icon";
import {
  addSubsidyApplicationPayNoticeApi,
  updateSubsidyApplicationPayNoticeBySubsidyApplicationPayNoticeIdApi,
  getSubsidyApplicationPayNoticeListBySubsidyApplicationIdApi,
  getSubsidyApplicationPayNoticeBySubsidyApplicationPayNoticeIdApi,
  deleteSubsidyApplicationPayNoticeBySubsidyApplicationPayNoticeIdApi,
} from "~/api/lindi/subsidyApplicationPayNotice";

import { deleteFileApi } from "~/api/basic/file.js";
import uploadFile from "~/components/uploadFile/index.vue";
import { fileSource } from "~/utils/sys.js";

// 定义props
const props = defineProps({
  subsidyApplicationId: {
    type: String,
    required: true,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  townItemList: {
    type: Array,
    default: () => [],
  },
});

// 全局实例
const { proxy } = getCurrentInstance();

// 响应式数据
const loading = ref(false);
const saveLoading = ref(false);
const editLoading = ref(false);
const editModalVisible = ref(false);
const previewModalVisible = ref(false);
const editFormRef = ref(null);
const fileUploadRef = ref(null);
const previewFile = ref(null);

// 支付通知列表数据
const paymentNoticeList = ref([]);

// 已有附件列表
const existingFiles = ref([]);

// 新上传的文件ID列表（用于清理未提交的文件）
const newUploadedFileIds = ref([]);

// 折叠状态管理
const collapsedItems = ref(new Set());

// 切换折叠状态
const toggleCollapse = (noticeId) => {
  const newCollapsed = new Set(collapsedItems.value);
  if (newCollapsed.has(noticeId)) {
    newCollapsed.delete(noticeId);
  } else {
    newCollapsed.add(noticeId);
  }
  collapsedItems.value = newCollapsed;
};

// 检查是否折叠
const isCollapsed = (noticeId) => {
  return collapsedItems.value.has(noticeId);
};

// 获取默认的镇街支付明细列表
const getDefaultTownPaymentList = () => {
  const townList = [
    { code: "350582001", name: "青阳街道" },
    { code: "350582002", name: "梅岭街道" },
    { code: "350582003", name: "新塘街道" },
    { code: "350582004", name: "罗山街道" },
    { code: "350582005", name: "灵源街道" },
    { code: "350582006", name: "永和镇" },
    { code: "350582007", name: "安海镇" },
    { code: "350582008", name: "东石镇" },
    { code: "350582009", name: "英林镇" },
    { code: "350582010", name: "金井镇" },
    { code: "350582011", name: "龙湖镇" },
    { code: "350582012", name: "深沪镇" },
    { code: "350582013", name: "西园街道" },
    { code: "350582014", name: "池店镇" },
    { code: "350582015", name: "陈埭镇" },
    { code: "350582016", name: "紫帽镇" },
    { code: "350582017", name: "内坑镇" },
    { code: "350582018", name: "西滨镇" },
    { code: "350582019", name: "磁灶镇" },
  ];

  return townList.map((town) => {
    // 计算该镇街的已支付比例
    const paidRatio = getPaidPaymentRatio(town.name);
    const remainingRatio = Math.max(0, 100 - paidRatio);
    
    // 从props.townItemList中获取对应镇街的详细信息
    const townItem = props.townItemList.find(item => item.townName === town.name);
    
    return {
      townName: town.name,
      totalAmount: townItem ? parseFloat(townItem.totalAmount) || 0 : 0,
      remainingPaymentRatio: remainingRatio,
      currentPaymentRatio: "",
      currentPaymentAmount: 0,
      remark: "",
    };
  });
};

// 合并现有镇街数据和默认镇街列表
const mergeWithDefaultTownList = (existingList = []) => {
  const defaultList = getDefaultTownPaymentList();
  const existingMap = new Map();

  // 将现有数据按镇街名称建立映射
  existingList.forEach((item) => {
    if (item.townName) {
      existingMap.set(item.townName, item);
    }
  });

  // 合并数据：如果默认镇街在现有数据中存在，使用现有数据；否则使用默认数据
  const mergedList = defaultList.map((defaultItem) => {
    const existingItem = existingMap.get(defaultItem.townName);
    return existingItem ? { ...existingItem } : { ...defaultItem };
  });

  // 添加不在默认列表中的现有镇街数据
  existingList.forEach((item) => {
    if (
      item.townName &&
      !defaultList.some((d) => d.townName === item.townName)
    ) {
      mergedList.push({ ...item });
    }
  });

  return mergedList;
};

// 编辑表单
const editForm = reactive({
  subsidyApplicationPayNotice: null,
  subsidyApplicationId: null,
  noticeName: "",
  noticeDate: "",
  payTitle: "",
  payExplain: "",
  townPaymentList: [],
  remark: "",
});

// 表单验证规则
const editRules = {
  noticeName: [{ required: true, message: "请输入通知名称" }],
  noticeDate: [{ required: true, message: "请选择通知时间" }],
  payExplain: [{ required: false }],
  townPaymentList: [
    {
      required: true,
      validator: (value, callback) => {
        if (!value || value.length === 0) {
          callback("请至少添加一条镇街支付明细");
        } else {
          callback();
        }
      },
    },
  ],
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return "";
  const units = ["B", "KB", "MB", "GB"];
  let index = 0;
  let fileSize = size;

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }

  return `${fileSize.toFixed(2)} ${units[index]}`;
};

// 判断是否为图片文件
const isImageFile = (fileName) => {
  if (!fileName) return false;
  const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"];
  const extension = fileName.toLowerCase().substring(fileName.lastIndexOf("."));
  return imageExtensions.includes(extension);
};

// 计算单个支付通知的合计数据
const getNoticeTotal = (notice, field) => {
  if (!notice?.townPaymentList) return 0;
  return notice.townPaymentList
    .reduce((sum, item) => sum + (parseFloat(item[field]) || 0), 0)
    .toFixed(2);
};

// 计算属性 - 编辑模式的合计数据

const editTotalAmount = computed(() => {
  if (
    !townPaymentDisplayList.value ||
    townPaymentDisplayList.value.length === 0
  ) {
    return 0;
  }
  return townPaymentDisplayList.value
    .reduce((sum, item) => {
      return sum + (parseFloat(item.totalAmount) || 0);
    }, 0)
    .toFixed(2);
});

const editCurrentTotalPaymentAmount = computed(() => {
  if (
    !townPaymentDisplayList.value ||
    townPaymentDisplayList.value.length === 0
  ) {
    return 0;
  }
  return townPaymentDisplayList.value
    .reduce((sum, item) => {
      return sum + (parseFloat(item.currentPaymentAmount) || 0);
    }, 0)
    .toFixed(2);
});

// 计算剩余支付比例
const getRemainingPaymentRatio = (townName) => {
  if (!townName || !paymentNoticeList.value.length) {
    return 100; // 如果没有历史记录，剩余比例为100%
  }

  // 计算该镇街的已支付比例总和
  const paidRatio = paymentNoticeList.value
    .filter(
      (notice) => notice.townPaymentList && notice.townPaymentList.length > 0
    )
    .flatMap((notice) => notice.townPaymentList)
    .filter((payment) => payment.townName === townName)
    .reduce(
      (sum, payment) => sum + (parseFloat(payment.currentPaymentRatio) || 0),
      0
    );

  // 剩余比例 = 100% - 已支付比例
  const remaining = Math.max(0, 100 - paidRatio);
  return remaining.toFixed(1);
};

// 计算当前支付金额
const calculateCurrentPaymentAmount = (record) => {
  const totalAmount = parseFloat(record.totalAmount) || 0;
  const currentPaymentRatio = parseFloat(record.currentPaymentRatio) || 0;
  record.currentPaymentAmount = (
    (totalAmount * currentPaymentRatio) /
    100
  ).toFixed(2);
};

// 镇街选择变化处理
const onTownChange = (record) => {
  // 根据选择的镇街获取对应的验收亩数、总金额和剩余支付比例
  const townData = getTownDataByName(record.townName);
  if (townData) {
    record.acceptAcreage = townData.acceptAcreage;
    record.totalAmount = townData.totalAmount;
    record.remainingPaymentRatio = townData.remainingPaymentRatio;
    // 重新计算当前支付金额
    calculateCurrentPaymentAmount(record);
  }
};

// 计算指定镇街的已支付比例
const getPaidPaymentRatio = (townName) => {
  // 从已有的支付通知中计算该镇街的累计支付比例
  let totalPaidRatio = 0;

  if (paymentNoticeList.value && paymentNoticeList.value.length > 0) {
    paymentNoticeList.value.forEach((notice) => {
      // 如果是编辑模式，排除当前正在编辑的支付通知
      if (
        editForm.subsidyApplicationPayNotice &&
        notice.subsidyApplicationPayNoticeId ===
          editForm.subsidyApplicationPayNotice
      ) {
        return; // 跳过当前编辑的支付通知
      }

      if (notice.townPaymentList && notice.townPaymentList.length > 0) {
        const townPayment = notice.townPaymentList.find(
          (item) => item.townName === townName
        );
        if (townPayment) {
          // 兼容前端字段currentPaymentRatio和后端字段paymentRadio
          const paymentRatio = townPayment.currentPaymentRatio || townPayment.paymentRadio;
          if (paymentRatio) {
            totalPaidRatio += parseFloat(paymentRatio) || 0;
          }
        }
      }
    });
  }

  return totalPaidRatio;
};

// 根据镇街名称获取镇街数据
const getTownDataByName = (townName) => {
  // 从props.townItemList中查找对应镇街的数据
  const townItem = props.townItemList.find(
    (item) => item.townName === townName
  );

  if (townItem) {
    // 计算已支付比例
    const paidRatio = getPaidPaymentRatio(townName);
    const remainingRatio = Math.max(0, 100 - paidRatio);

    return {
      acceptAcreage: parseFloat(townItem.acceptAcreage) || 0,
      totalAmount: parseFloat(townItem.totalAmount) || 0,
      remainingPaymentRatio: remainingRatio,
    };
  }

  // 如果没找到对应镇街数据，返回默认值
  return {
    acceptAcreage: 0,
    totalAmount: 0,
    remainingPaymentRatio: 100,
  };
};

// 添加镇街支付明细项
const addTownPaymentItem = () => {
  editForm.townPaymentList.push({
    townName: "",
    acceptAcreage: 0,
    totalAmount: 0,
    remainingPaymentRatio: 0,
    currentPaymentRatio: "",
    currentPaymentAmount: 0,
    remark: "",
  });
};

// 可选择的镇街列表 - 从props.townItemList中获取
const availableTowns = computed(() => {
  return props.townItemList.map((item) => ({
    value: item.townName,
    label: item.townName,
  }));
});

// 镇街支付明细显示列表 - 包含所有镇街
const townPaymentDisplayList = ref([]);

// 初始化镇街支付明细显示列表
const initTownPaymentDisplayList = () => {
  // 如果是新增模式且editForm.townPaymentList有数据，直接使用editForm.townPaymentList
  if (!editForm.subsidyApplicationPayNotice && editForm.townPaymentList.length > 0) {
    townPaymentDisplayList.value = editForm.townPaymentList.map((item) => {
      // 从props.townItemList中获取对应镇街的详细信息
      const townItem = props.townItemList.find(t => t.townName === item.townName);
      
      return reactive({
        townName: item.townName,
        acceptAcreage: townItem ? parseFloat(townItem.acceptAcreage) || 0 : 0,
        totalAmount: townItem ? parseFloat(townItem.totalAmount) || 0 : 0,
        remainingPaymentRatio: item.remainingPaymentRatio || 100,
        currentPaymentRatio: item.currentPaymentRatio || "",
        currentPaymentAmount: item.currentPaymentAmount || 0,
        remark: item.remark || "",
      });
    });
  } else {
    // 编辑模式或其他情况，使用props.townItemList
    townPaymentDisplayList.value = props.townItemList.map((townItem) => {
      // 查找是否已有该镇街的支付记录
      const existingPayment = editForm.townPaymentList.find(
        (item) => item.townName === townItem.townName
      );

      // 计算已支付比例和剩余支付比例
      const paidRatio = getPaidPaymentRatio(townItem.townName);
      const remainingRatio = Math.max(0, 100 - paidRatio);

      return reactive({
        townName: townItem.townName,
        acceptAcreage: parseFloat(townItem.acceptAcreage) || 0,
        totalAmount: parseFloat(townItem.totalAmount) || 0,
        remainingPaymentRatio: remainingRatio,
        currentPaymentRatio: existingPayment?.currentPaymentRatio || "",
        currentPaymentAmount: existingPayment?.currentPaymentAmount || 0,
        remark: existingPayment?.remark || "",
      });
    });
  }
};

// 删除镇街支付明细项
const removeTownPaymentItem = (index) => {
  editForm.townPaymentList.splice(index, 1);
};

// 显示编辑弹窗
const showEditModal = async (notice = null) => {
  try {
    editLoading.value = true;

    if (notice) {
      // 编辑模式 - 通过API获取详细信息
      const response =
        await getSubsidyApplicationPayNoticeBySubsidyApplicationPayNoticeIdApi(
          notice.subsidyApplicationPayNoticeId
        );

      if (response) {
        const noticeDetail = response;
        editForm.subsidyApplicationPayNotice =
          noticeDetail.subsidyApplicationPayNoticeId;
        editForm.subsidyApplicationId = noticeDetail.subsidyApplicationId;
        editForm.noticeName = noticeDetail.noticeName || "";
        editForm.noticeDate = noticeDetail.noticeDate;
        editForm.payTitle = noticeDetail.payTitle || "";
        editForm.payExplain = noticeDetail.payExplain || "";
        editForm.townPaymentList = mergeWithDefaultTownList(
          noticeDetail.townPaymentList || []
        );
        editForm.remark = noticeDetail.remark || "";

        // 设置已有附件
        existingFiles.value = noticeDetail.fileVOList || [];

        // 初始化镇街支付明细显示列表（编辑模式）
        initTownPaymentDisplayList();
      } else {
        throw new Error("获取支付通知详情失败");
      }
    } else {
      // 新增模式
      resetFormData();
      // 新增模式下，初始化19个镇街记录
      editForm.townPaymentList = getDefaultTownPaymentList();
    }

    // 初始化镇街支付明细显示列表
    initTownPaymentDisplayList();

    editModalVisible.value = true;
  } catch (error) {
    console.error("显示编辑弹窗失败:", error);
    Message.error("加载数据失败");
  } finally {
    editLoading.value = false;
  }
};

// 删除支付通知
const deletePaymentNotice = (notice, index) => {
  proxy.$modal.confirm({
    title: "确认删除",
    content: `确定要删除支付通知 ${index + 1} 吗？`,
    onOk: async () => {
      try {
        await deleteSubsidyApplicationPayNoticeBySubsidyApplicationPayNoticeIdApi(
          notice.subsidyApplicationPayNoticeId
        );
        paymentNoticeList.value.splice(index, 1);
        Message.success("删除成功");
      } catch (error) {
        console.error("删除支付通知失败:", error);
        Message.error("删除失败");
      }
    },
  });
};

// 清理未使用的文件
const cleanupUnusedFiles = () => {
  const deletePromises = newUploadedFileIds.value.map((fileId) => {
    return deleteFileApi(fileId).catch((error) => {
      console.error("删除文件失败:", error);
      return null;
    });
  });

  return Promise.all(deletePromises).then(() => {
    newUploadedFileIds.value = [];
  });
};

// 重置编辑表单
const resetEditForm = () => {
  // 清理未提交的文件
  if (newUploadedFileIds.value.length > 0) {
    return cleanupUnusedFiles()
      .then(() => {
        resetFormData();
      })
      .catch((error) => {
        console.error("清理文件失败:", error);
        resetFormData();
      });
  } else {
    resetFormData();
    return Promise.resolve();
  }
};

// 重置表单数据
const resetFormData = () => {
  editForm.subsidyApplicationPayNotice = null;
  editForm.subsidyApplicationId = null;
  editForm.noticeName = "";
  editForm.noticeDate = "";
  editForm.payTitle = "";
  editForm.payExplain = "";
  editForm.townPaymentList = [];
  editForm.remark = "";
  existingFiles.value = [];
  newUploadedFileIds.value = [];

  // 重置文件上传组件
  if (fileUploadRef.value) {
    fileUploadRef.value.fileList = [];
  }

  editModalVisible.value = false;
};

// 处理文件上传成功
const handleUploadSuccess = (response) => {
  if (response && response.fileId) {
    // 将新上传的文件ID添加到追踪列表
    newUploadedFileIds.value.push(response.fileId);
    console.log("文件上传成功:", response);
  }
};

// 移除已有附件
const removeExistingFile = (file) => {
  const index = existingFiles.value.findIndex(
    (item) => (item.id || item.fileId) === (file.id || file.fileId)
  );
  if (index > -1) {
    existingFiles.value.splice(index, 1);
  }
};

// 保存支付通知
const handleSave = () => {
  // 同步townPaymentDisplayList数据到editForm.townPaymentList
  // 在编辑模式下，保留所有镇街数据；在新增模式下，只保留有支付比例的数据
  if (editForm.subsidyApplicationPayNotice) {
    // 编辑模式：保留所有镇街数据，包括支付比例为0的记录
    editForm.townPaymentList = townPaymentDisplayList.value.map((item) => ({
      townName: item.townName,
      acceptAcreage: item.acceptAcreage,
      totalAmount: item.totalAmount,
      remainingPaymentRatio: item.remainingPaymentRatio,
      paymentRadio: item.currentPaymentRatio || 0, // 前端字段currentPaymentRatio映射为后端字段paymentRadio
      currentPaymentAmount: item.currentPaymentAmount || 0,
      remark: item.remark || '',
    }));
  } else {
    // 新增模式：只保留有支付比例的数据
    editForm.townPaymentList = townPaymentDisplayList.value
      .filter(
        (item) =>
          item.currentPaymentRatio && parseFloat(item.currentPaymentRatio) > 0
      )
      .map((item) => ({
        townName: item.townName,
        acceptAcreage: item.acceptAcreage,
        totalAmount: item.totalAmount,
        remainingPaymentRatio: item.remainingPaymentRatio,
        paymentRadio: item.currentPaymentRatio, // 前端字段currentPaymentRatio映射为后端字段paymentRadio
        currentPaymentAmount: item.currentPaymentAmount,
        remark: item.remark,
      }));
  }

  // 验证镇街支付明细
  if (!editForm.townPaymentList || editForm.townPaymentList.length === 0) {
    Message.error("请至少添加一条支付明细");
    return;
  }

  // 镇街明细校验已移除

  editFormRef.value
    .validate()
    .then(() => {
      saveLoading.value = true;

      // 准备提交的数据
      const submitData = {
        subsidyApplicationId: props.subsidyApplicationId,
        noticeName: editForm.noticeName,
        noticeDate: editForm.noticeDate,
        payTitle: editForm.payTitle,
        payExplain: editForm.payExplain,
        townPaymentList: editForm.townPaymentList,
      };

      // 处理附件
      const attachments = [];
      const fileIds = [];

      // 添加已有附件
      existingFiles.value.forEach((file) => {
        attachments.push({
          subsidyApplicationPayNoticeAttachmentId:
            file.subsidyApplicationPayNoticeAttachmentId,
          fileId: file.fileId,
        });
        fileIds.push(file.fileId);
      });

      // 添加新上传的附件
      newUploadedFileIds.value.forEach((fileId) => {
        attachments.push({
          fileId: fileId,
        });
        fileIds.push(fileId);
      });

      // 设置fileList为逗号分隔的文件ID字符串
      submitData.fileList = fileIds.join(",");
      // 设置fileVOList为附件对象数组（用于兼容）
      submitData.fileVOList = attachments;

      // 调用API
      let apiPromise;
      if (editForm.subsidyApplicationPayNotice) {
        // 更新支付通知
        submitData.subsidyApplicationPayNoticeId =
          editForm.subsidyApplicationPayNotice;
        apiPromise =
          updateSubsidyApplicationPayNoticeBySubsidyApplicationPayNoticeIdApi(
            submitData
          );
      } else {
        // 新增支付通知
        apiPromise = addSubsidyApplicationPayNoticeApi(submitData);
      }

      return apiPromise;
    })
    .then((response) => {
      // 保存成功后清空新上传文件ID列表
      newUploadedFileIds.value = [];
      Message.success(
        editForm.subsidyApplicationPayNotice ? "编辑成功" : "新增成功"
      );

      // 重新加载支付通知列表
      loadPaymentNotice();

      editModalVisible.value = false;
      resetEditForm();
    })
    .catch((error) => {
      console.error("保存失败:", error);
      Message.error("表单验证失败，请检查输入");
    })
    .finally(() => {
      saveLoading.value = false;
    });
};

// 下载文件
const downloadFile = (file) => {
  console.log("下载文件:", file);
  Message.info("文件下载功能待实现");
};

// 预览文件（已改为直接跳转链接）
// const previewFileHandler = (file) => {
//   previewFile.value = file;
//   previewModalVisible.value = true;
// };

// 加载支付通知数据
const loadPaymentNotice = () => {
  if (!props.subsidyApplicationId) {
    return Promise.resolve();
  }

  loading.value = true;

  return getSubsidyApplicationPayNoticeListBySubsidyApplicationIdApi(
    props.subsidyApplicationId
  )
    .then((response) => {
      if (response) {
        console.log(response);
        paymentNoticeList.value = response;
        console.log("paymentNoticeList", paymentNoticeList.value);
      } else {
        paymentNoticeList.value = [];
      }
    })
    .catch((error) => {
      console.error("获取支付通知失败:", error);
      paymentNoticeList.value = [];
      Message.error("获取支付通知失败");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 组件挂载时加载数据
onMounted(() => {
  loadPaymentNotice();
});
</script>

<style scoped>
.payment-notice-container {
  padding: 0;
}

.notice-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 8px;
}

/* 支付通知列表样式 */
.notice-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.notice-item {
  width: 100%;
}

.notice-item-card {
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.notice-item-card:hover {
  border-color: #165dff;
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.1);
}

.notice-title {
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
}

.notice-title:hover {
  color: #165dff;
}

.collapse-icon {
  font-size: 14px;
  transition: transform 0.3s ease;
}

.notice-content {
  padding: 16px 0;
}

.notice-descriptions {
  margin-bottom: 24px;
}

.amount-text {
  font-size: 18px;
  font-weight: 600;
  color: #f53f3f;
}

.time-text {
  font-size: 14px;
  color: #4e5969;
}

.description-text {
  font-size: 14px;
  color: #86909c;
  line-height: 1.6;
}

.attachments-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e6eb;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f7f8fa;
  border-radius: 6px;
  border: 1px solid #e5e6eb;
  transition: all 0.2s;
}

.attachment-item:hover {
  background: #f2f3f5;
  border-color: #c9cdd4;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.file-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
  color: #86909c;
}

.file-details {
  flex: 1;
}

.file-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
  line-height: 1.4;
}

.file-size {
  margin: 0;
  font-size: 12px;
  color: #86909c;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.empty-attachments,
.empty-notice {
  margin: 24px 0;
}

.empty-edit-details {
  margin: 16px;
  min-height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #e5e6eb;
  border-radius: 4px;
  background: #fafbfc;
}

.empty-details {
  margin: 24px 0;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  background: #fafbfc;
}

/* 支付明细表格样式 */
.payment-details-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e6eb;
}

.payment-table {
  margin-bottom: 16px;
}

.payment-summary {
  padding: 16px;
  background: #f7f8fa;
  border-radius: 6px;
  border: 1px solid #e5e6eb;
}

.summary-descriptions {
  margin: 0;
}

.summary-text {
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
}

.summary-amount-text {
  font-size: 16px;
  font-weight: 600;
  color: #165dff;
}

.current-total-amount-text {
  font-size: 16px;
  font-weight: 600;
  color: #f53f3f;
}

.current-amount-text {
  font-size: 14px;
  font-weight: 500;
  color: #f53f3f;
}

.edit-modal-content {
  padding: 8px 0;
}

.upload-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  font-size: 12px;
  color: #86909c;
}

.tip-icon {
  font-size: 14px;
}

/* 镇街支付明细编辑样式 */
.town-payment-edit-section {
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  overflow: hidden;
}

.edit-table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f7f8fa;
  border-bottom: 1px solid #e5e6eb;
}

.edit-table-title {
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
}

.edit-table-container {
  padding: 16px;
}

.edit-payment-table {
  margin-bottom: 16px;
}

.current-payment-display {
  font-size: 12px;
  font-weight: 500;
  color: #f53f3f;
}

.remaining-ratio-display {
  font-size: 12px;
  font-weight: 500;
  color: #00b42a;
  background: #f6ffed;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #b7eb8f;
}

.readonly-field {
  display: inline-block;
  padding: 4px 8px;
  background: #f7f8fa;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  color: #4e5969;
  font-size: 14px;
  min-height: 32px;
  line-height: 24px;
  font-weight: 500;
}

.edit-payment-summary {
  padding: 12px 16px;
  background: #f7f8fa;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.edit-summary-descriptions {
  margin: 0;
}

.edit-summary-text {
  font-size: 12px;
  font-weight: 500;
  color: #1d2129;
}

.edit-summary-amount-text {
  font-size: 14px;
  font-weight: 600;
  color: #165dff;
}

.edit-current-total-amount-text {
  font-size: 14px;
  font-weight: 600;
  color: #f53f3f;
}

/* 已有附件样式 */
.existing-files-section {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px dashed #e5e6eb;
  margin-top: 16px;
}

.existing-files-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.existing-files-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.existing-file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f7f8fa;
  border-radius: 6px;
  border: 1px solid #e5e6eb;
  transition: all 0.2s;
}

.existing-file-item:hover {
  background: #f2f3f5;
  border-color: #c9cdd4;
}

.edit-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e5e6eb;
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notice-descriptions {
    grid-template-columns: 1fr !important;
  }

  .attachment-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .file-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
